package com.tingyuge.thinking.spring.configuration.bean.scope;


import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.NonNull;

import java.util.HashMap;
import java.util.Map;

/**
 * ThreadLocal 级别的scope
 * @author xiaodao
 * @version 1.0
 * @date 2021/7/10
 */
public class ThreadLocalScope implements Scope {
    public static final String scope_name = "thread-local";

    private final static NamedThreadLocal<Map<String, Object>> threadLocal = new NamedThreadLocal<Map<String, Object>>("thread-local-scope"){

        public Map<String, Object> initialValue() {
            return new HashMap<>();
        }
    };
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        //非空
        Map<String, Object> context = getContext();
        Object object = context.get(name);
        if(null == object){
            object =  objectFactory.getObject();
            context.put(name,object);
        }
        return object;
    }

    @NonNull
    private Map<String,Object> getContext(){
        Thread t = Thread.currentThread();
        return threadLocal.get();
    }

    @Override
    public Object remove(String name) {
        Map<String, Object> context = getContext();
        return    context.remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
    //TODO
    }

    @Override
    public Object resolveContextualObject(String key) {
        return getContext().get(key);
    }

    @Override
    public String getConversationId() {
        return String.valueOf(Thread.currentThread().getId());
    }
}
